<?php
namespace app\api\controller;
use app\api\Controller\Base;
use think\Db;
class Index extends Base
{
    public function index()
    {
        return json(['code'=>200,'msg'=>'请求错误']);
    }
	/**
 	 * POST
	 * 员工登录
	 */
	public function login(){
        $where['a.tel'] = $_POST['mobile'];
		//file_put_contents("a.txt", input());
		$where['a.password'] = md5_salt($_POST['password']);
        $member = db('emp')->alias("a")->join("store b","a.store_name_id=b.id","LEFT")
        ->where($where)
        ->field("a.*,b.store_name")
        ->find();
        if ($member) {
        	//插入登录记录
        	$time = now_time();
        	$request = \think\Request::instance();
        	$data['ip'] = $request->ip();//操作ip
        	$data['emp_id']=$member['id'];
			$data['login_time'] = $time;
			$aa = db('emp_log')->insert($data);
			db('emp')->where('id',$member['id'])->update(['login_time'=>$time]);
			unset($member['password']);
			$member['login_time']=$time;
            return json(["code"=>200,"msg"=>'登录成功',"member"=>$member]);
        } else {
			return json(["code"=>408,"msg"=>'用户或密码错误']);
        }
	}
	//预定管理数据
	public function yd_list(){
		$start_time=$_POST['start_time'];
		$end_time=$_POST['end_time'];
		$store_id=$_POST['store_id'];
		$sum=db("room_sort")->where("store_id",$store_id)->sum('room_num');
		$data=[];
		for($i=1;$i<=10;$i++){
			$where['start_time']=["<=",$start_time];
			$where['end_time']=[">=",$start_time];
			$where['store_id']=$store_id;
			$where['state']=2;  //已经支付
			$ys=db("reserve")->where($where)->sum('room_num');
			$data[$start_time]['time']=$start_time;
			$data[$start_time]['day']=date('d',strtotime($start_time));
			$data[$start_time]['ys']=$ys;
			$data[$start_time]['ws']=$sum-$ys;
			$start_time=add_days($start_time, 1);
		}	
		
		return json(['data'=>$data]);
	}
	//预订详情
	public function yd_detail(){
		$store_id=$_POST['store_id'];
		$start_time=$_POST['start_time'];
		//房店所有房间
		$list=db("room_sort")->where("store_id",$store_id)->field("room_name,id as room_id,room_num")->select();
		$total=db("room_sort")->where("store_id",$store_id)->sum('room_num');
		$where['a.start_time']=["<=",$start_time];
		$where['a.end_time']=[">=",$start_time];
		$where['a.store_id']=$store_id;
		$where['a.state']=2;  //已经支付
		
		$room = db('reserve')->alias('a')->field('sum(a.room_num) as z_num,a.*')->where($where)->group('room_id')->buildSql();
		//预定房间详情
		$list2=db("room_sort")->alias('b')->join("$room a",'a.room_id=b.id','LEFT')->field("a.room_id,a.room_num as ys,b.room_name,b.room_num,a.z_num")->where($where)->select();  //当天所有预定的房间
		$total_ys =db("reserve")->alias('a')->where($where)->sum('a.room_num');  //总预定数量
		$total_ws=$total-$total_ys;  //剩余数量
		
		$list3=array();
		foreach($list2 as $k2=>$v2){
			$list3[$v2['room_id']]=$v2['z_num'];
		}
		//剩余房间详情
		foreach($list as $k=>$v){
			$room_id=$v['room_id'];
			$ys=0;
			$ws=0;
			if(isset($list3[$room_id])){
				$ys=$list3[$room_id];
				$ws=$v['room_num']-$ys;
			}
			$list[$k]['ys']=$ys;
			$list[$k]['ws']=$ws==0?$v['room_num']:$ws;
		}
		return json(['data'=>$list,'data2'=>$list2,'total_ys'=>$total_ys,'total_ws'=>$total_ws]);
	}
	
	//获取会员信息
	public function get_userinfo(){
		$no=$_POST['no'];
		if(!$no){
			return json(['code'=>404,'msg'=>'会员码无效1!']);
		}
		$user=db("user")->where("no",$no)->find();
		if(!$user){
			return json(['code'=>404,'msg'=>'会员码无效2!']);
		}
		//折扣
		$level['discount']=0;
		if($user['level_id']>0){
			$level=db("storediscount")->where(["store_name_id"=>$_POST['store_id'],'userlevel'=>$user['level_id']])->find();
		}
		$no_time=$user['no_time'];
		$res=timediff(strtotime($no_time),time());
//		if($res['min']>=25){
//			return json(['code'=>404,'msg'=>'会员码已过期,请重新打开扫码!']);
//		}
		return json(['code'=>200,'user'=>$user,'level'=>$level]);
	}
	
	/**
	 * 会员卡收款
	 * */
	public function shouk(){
		$user_info = db('user')->alias('a')->join('userlevel b','a.level_id=b.id','LEFT')->where('a.id',$_POST['user_id'])->field('a.balance,a.level_id,a.id,a.mobile,a.user_name,b.name as level_name,b.discount')->find();
		//折扣
		$discount=0;
		if($user_info['level_id']>0){
			$discount=db("storediscount")->where(["store_name_id"=>$_POST['store_id'],'userlevel'=>$user_info['level_id']])->value('discount');
		}
		
		$origin_price=$_POST['price'];
		$balance=$_POST['price'];
		if($discount>0){
			$zk = $discount/100;//折扣
			$origin_price =  $_POST['price'];//应付金额
			$np_price = $_POST['np_price'];//不参与抵扣金额
			$price = ($origin_price-$np_price)*$zk;//参与折扣金额
			$balance =($origin_price-$np_price)-$price+$np_price;  //实际支付
		}
		
		if($user_info['balance']<$balance){
			return json(['code'=>400,"msg"=>'会员卡余额不足']);
		}
		
		//订单信息
		Db::startTrans();
		$res=[];
		$order_sn = order_create_no();
		$res[]=cashier_pay_log($_POST['store_id'],$_POST['user_id'],$balance,9,$order_sn,5,'会员卡支付',2,$user_info['level_id'],$origin_price,$_POST['staff_id']);//订单日志
		$paylog = db('paylog')->where('order_sn',$order_sn)->find();
		$res[]=db('user')->where('id',$paylog['user_id'])->setDec('balance',$paylog['balance']);  //更新用户表
		$res[]=db('paylog')->where('id',$paylog['id'])->update(['state'=>2,'pay_time'=>now_time()]);//更新支付表
		$res[]=card_xf_log($paylog['order_sn'],$paylog['user_id'],0,$paylog['balance'],$paylog['level_id'],$paylog['pay_type'],0,now_time(),2,0,'收银台会员卡支付');//会员卡消费
		if (in_array(false, $res)){
		    Db::rollback();
			return json(['code'=>400,"msg"=>'支付失败']);
		}else {
		    Db::commit();
			$order_id = db('paylog')->where('order_sn',$order_sn)->value('id');
			return json(['code'=>200,"msg"=>'支付成功','order_id'=>$order_id]);
		}
	}

	/**
	 * 记账收款
	 * */
	public function jz_pay(){
		$order_sn = order_create_no();
		$res = cashier_pay_log($_POST['store_id'],0,$_POST['balance'],6,$order_sn,$_POST['pay_type'],'收银台记账',2,0,$_POST['balance'],$_POST['staff_id']);//订单日志
		if(!$res){
			return json(['code'=>400,"msg"=>'记账失败']);
		}else {
			$order_id = db('paylog')->where('order_sn',$order_sn)->value('id');
			return json(['code'=>200,"msg"=>'记账成功','order_id'=>$order_id]);
		}
	}
	
	//获取会员所有可核销房券
	public function get_userhouse(){
		$no=$_POST['no'];
		if(!$no){
			return json(['code'=>404,'msg'=>'会员码无效!']);
		}
		$user=db("user")->where("no",$no)->find();
		$user_id = $user['id'];
		
		$is_no = 0;
		if(!$user){
			//判断是否通过订单号
			$is_no = 1;
			$where['type'] = 3;//客房预订
			$where['pay_type'] = array('in',array(2,5,6)); //微信支付，会员卡支付，卡券
			$where['state'] =2;//已支付
			$where['order_sn'] = $no;
			$order_id = db('paylog')->where($where)->value('id');
			if(!$order_id){
				return json(['code'=>404,'msg'=>'订单号无效!']);
			}
			$user['no_time'] = now_time();
			$userhouse = db('reserve')->alias('a')->join('room_sort b','a.room_id=b.id','LEFT')->field('a.store_id,a.id,a.user_id,a.room_num as num,b.room_name  as h_name')->where(['a.order_id'=>$order_id,'a.store_id'=>$_POST['store_id'],'a.room_num'=>array('gt',0),'a.is_hx'=>0])->select();
		}else{
			//只查询出可使用的房券
			$u_where['a.start_time'] = array('elt',date('Y-m-d',time()));
			$u_where['a.end_time'] = array('egt',date('Y-m-d',time()));
			$u_where['a.user_id'] = $user_id;
			$u_where['b.store_id'] = $_POST['store_id'];
			$u_where['a.num'] = array('gt',0);
			$userhouse = db('userhouse')->alias('a')->join('room_sort b','a.house_id=b.id','LEFT')->field('b.store_id,a.id,a.user_id,b.room_name as h_name,a.num')->where($u_where)->select();
		}
		
		if(!$userhouse){
			return json(['code'=>404,'msg'=>'暂无房券!']);
		}
		$no_time=$user['no_time'];
		$res=timediff(strtotime($no_time),time());
		if($res['min']>=25){
			return json(['code'=>404,'msg'=>'会员码已过期,请重新打开扫码!']);
		}
		return json(['code'=>200,'userhouse'=>$userhouse,'is_no'=>$is_no]);
	}
	
	//核销
	public function get_hengx(){
		Db::startTrans();
		$res = [];
		$level_id = db('user')->where('id',$_POST['user_id'])->value('level_id');
		if($_POST['is_no']==1){//客房预订订单
			$hx_id = $_POST['hx_id'][0];
			$res[]= db('reserve')->where('id',$hx_id)->update(['is_hx'=>1,'hx_time'=>now_time()]);
			//打印核销日志
			$reserve =  db('reserve')->alias('a')->field('b.id as order_id,b.order_sn,a.room_num,a.room_id')->join('paylog b','a.order_id=b.id','LEFT')->where('a.id',$hx_id)->find();
			$res[] = card_xf_log($reserve['order_sn'],$_POST['user_id'],$_POST['store_id'],0,0,6,$level_id,now_time(),4,$_POST['staff_id'],'房券核销',$reserve['room_num'],$reserve['room_id']);
			//订单表里面的核销
			$res[] = cashier_pay_log($_POST['store_id'],$_POST['user_id'],0,5,$reserve['order_sn'],6,'房券核销',2,$level_id,0,$_POST['staff_id'],$reserve['room_num'],$reserve['room_id']);
			$order_id = $reserve['order_id'];
		}else{//会员全部房券核销
			//只查询出可使用的房券
			$u_where['a.start_time'] = array('elt',date('Y-m-d',time()));
			$u_where['a.end_time'] = array('egt',date('Y-m-d',time()));
			$u_where['a.user_id'] = $_POST['user_id'];
			$u_where['b.store_id'] = $_POST['store_id'];
			$u_where['a.num'] = array('gt',0);
			$userhouse = db('userhouse')->alias('a')->join('room_sort b','a.house_id=b.id','LEFT')->field('b.store_id,a.id,a.user_id,b.room_name as h_name,a.num,b.id as room_id')->where($u_where)->select();
			$kaquan = 0;
			
			$order_sn = order_create_no();
			foreach($userhouse as $v=>$k){
				$kaquan +=$_POST['hx_num'][$v];
				if($_POST['hx_num'][$v]>$k['num']){
					return json(['code'=>400,"msg"=>$k['h_name'].'房间最多可核销'.$k['num'].'间']);
				}
				if($_POST['hx_num'][$v]>0){
					//减去相对应的房券
					$res[] = db('userhouse')->where('id',$_POST['hx_id'][$v])->setDec('num',$_POST['hx_num'][$v]);
					//打核销日志
					$res[] = card_xf_log($order_sn,$_POST['user_id'],$_POST['store_id'],0,0,6,$level_id,now_time(),4,$_POST['staff_id'],'房券核销',$_POST['hx_num'][$v],$k['room_id']);
				}
				$room_id = $k['room_id'];
			}
			//支付日志表核销日志
			$res[] = cashier_pay_log($_POST['store_id'],$_POST['user_id'],0,5,$order_sn,6,'房券核销',2,$level_id,0,$_POST['staff_id'],$kaquan,$room_id);
			//累加减去用户表里现有总房券
			$res[] = db('user')->where('id',$_POST['user_id'])->setDec('kaquan',$kaquan);
			$order_id = db('paylog')->where('order_sn',$order_sn)->value('id');
		}
		if(in_array(false, $res)){
			Db::rollback();
			return json(['code'=>400,"msg"=>'核销失败']);
		}else {
			Db::commit();
			return json(['code'=>200,"msg"=>'核销成功','order_id'=>$order_id]);
		}
		
	}

	/**
	 * 收营员交班
	 * */
	public function jiaoban(){
		$emp = $this->get_jiaoban($_POST['id'],$_POST['login_time']);
		return json(['emp'=>$emp]);
	}

	/**
	 * 交班数据查询
	 * $id 收银员id
	 * $login_time 收银员登录时间
	 * */
	public function get_jiaoban($id,$login_time){
		$where['b.add_time']=array('egt',$login_time);
		$where['a.id']=array('eq',$id);
		
		$tk=db('emp')->alias('a')->field('IFNULL(SUM(b.tk_money),0) as tk,count(b.id) as count_tk')->join('paylog b','a.id=b.staff_id','LEFT')->where($where)->where('type',4)->find(); //退款
		
		$where['b.type']=array('neq',4);   //退款
		$field = 'a.id as emp_id,c.id as store_id,d.id as group_id,a.login_time,a.name,c.store_name,d.principal as group_name,count(b.id) as count_order,IFNULL(SUM(b.origin_price)-SUM(b.tk_money),0) as origin_price,IFNULL(SUM(b.origin_price-b.balance),0) as yh_money,IFNULL(SUM(b.balance)-SUM(b.tk_money),0) as balance';
		$emp = db('emp')->alias('a')->field($field)->join('paylog b','a.id=b.staff_id','LEFT')->join('store c','a.store_name_id=c.id','LEFT')->join('group d','a.group_name_id=d.id')->where($where)->where('a.id',$_POST['id'])->find();
		$emp['now_time'] = now_time();
		$count_yh = 0;
		$yh = db('emp')->alias('a')->field('balance,origin_price')->join('paylog b','a.id=b.staff_id','LEFT')->where($where)->where('a.id',$_POST['id'])->select();
		foreach($yh as $y){
			if($y['origin_price']>$y['balance']){
				$count_yh+=$count_yh+1;
			}
		}
		$emp['count_yh'] = $count_yh;
		//各通道收款
		$emp['xj'] =db('emp')->alias('a')->field('count(b.id) as xj_count,IFNULL(SUM(b.balance),0) as xj_balance')->join('paylog b','a.id=b.staff_id','LEFT')->where($where)->where('pay_type',1)->find();//现金
		$emp['zfb'] =db('emp')->alias('a')->field('count(b.id) as zfb_count,IFNULL(SUM(b.balance),0) as zfb_balance')->join('paylog b','a.id=b.staff_id','LEFT')->where($where)->where('pay_type',3)->find();//支付宝
		$emp['wx'] =db('emp')->alias('a')->field('count(b.id) as wx_count,IFNULL(SUM(b.balance),0) as wx_balance')->join('paylog b','a.id=b.staff_id','LEFT')->where($where)->where('pay_type',2)->find();//微信
		$emp['yl'] =db('emp')->alias('a')->field('count(b.id) as yl_count,IFNULL(SUM(b.balance),0) as yl_balance')->join('paylog b','a.id=b.staff_id','LEFT')->where($where)->where('pay_type',8)->find();//银联
		
		//会员
		$emp['card_cz'] =db('emp')->alias('a')->field('IFNULL(SUM(b.balance),0) as card_cz,count(b.id) as count_cz')->join('paylog b','a.id=b.staff_id','LEFT')->where($where)->where('type',2)->find(); //会员充值
		$emp['card_xf'] =db('emp')->alias('a')->field('IFNULL(SUM(b.balance),0) as card_xf,count(b.id) as count_xf')->join('paylog b','a.id=b.staff_id','LEFT')->where($where)->where('pay_type',5)->find(); //会员支付
		
		//房券
		$f_where['staff_id']=$id;
		$f_where['time']=array('egt',$login_time);
		$emp['fq_zs'] =db('consume')->field('IFNULL(SUM(num),0) as zs_num,count(id) as count_zs')->where($f_where)->where('type',3)->find(); //房券赠送
		$emp['fq_hx'] =db('consume')->field('IFNULL(SUM(num),0) as hx_num,count(id) as count_hx')->where($f_where)->where('type',4)->find(); //房券核销
		
		//退款
		$emp['tk'] = $tk;
		return $emp;
	}

	/**
	 *交班并退出
	 * */
	public function end_jiaoban(){
		$emp = $this->get_jiaoban($_POST['id'],$_POST['login_time']);
		//交班日志
		$res = jiaoban_log($emp);
		if($res){
			return json(['code'=>200,"msg"=>'']);
		}else{
			return json(['code'=>400,"msg"=>'']);
		}
	}

	/**
	 * 收银员修改密码
	 * */
	public function up_pwd(){
		$where['id'] = $_POST['id'];
		$where['password'] = md5_salt($_POST['y_pwd']);
        $member = db('emp')->where($where)->find();
		if(!$member){
			return json(['code'=>400,"msg"=>'原密码不正确']);
		}
		$update['password'] =  md5_salt($_POST['up_pwd']);
		$res = db('emp')->where('id',$_POST['id'])->update($update);
		if($res){
			return json(['code'=>200,"msg"=>'修改密码成功']);
		}else{
			return json(['code'=>400,"msg"=>'修改密码失败']);
		}
	}

	/**
	 * 桌面收银会员充值
	 * */
	public function card_cz(){
		$level_id = db('user')->where('id',$_POST['user_id'])->value('level_id');
		if($level_id<=0){
			return json(['code'=>400,"msg"=>'该会员还未办理会员卡']);
		}
		$order_sn = order_create_no();
		$rest=card_cz_log($_POST['store_id'],$_POST['user_id'],$_POST['cz_money'],2,$order_sn,0,'会员卡充值',1,$_POST['staff_id']);
		return json(['code'=>200,'order_sn'=>$order_sn]);
	}
	
	/**
	 * 会员卡充值确认收款
	 * */
	public function card_que(){
		$pay_type=get_bartype($_POST["mem_card"]);//判断是微信还是支付宝打开
		db('paylog')->where('order_sn',$_POST['order_sn'])->update(['pay_type'=>$pay_type]);
		$paylog = db('paylog')->where('order_sn',$_POST['order_sn'])->find();
		if($paylog['state']==2){
			return json(['code'=>200,"msg"=>'会员充值收款成功','order_id'=>$paylog['id']]);
		}
		Db::startTrans();
		$res=[];
//		$up['balance']=['inc',$paylog['balance']];
//		$up['total_chongzhi']=['inc',$paylog['balance']];
//		$up['total_count']=['inc',1];
//		$res[]=db('user')->where('id',$paylog['user_id'])->update($up);
//		$res[]=card_xf_log($paylog['order_sn'],$paylog['user_id'],0,$paylog['balance'],$paylog['level_id'],$paylog['pay_type'],0,now_time(),1,0,'会员充值');
//		$res[]=db('paylog')->where('id',$paylog['id'])->update(['state'=>2,'pay_time'=>now_time()]);
		$result=bar_pay($_POST["mem_card"],'H480','ea4f13f136c95a617b1acfbda7af6eb1','45a7a757b685f5c890b815839e58ca18',$paylog['balance'],1,$paylog['order_sn'],'');
		if ($result==2 && in_array(false, $res)){
			Db::rollback();
			return json(['code'=>400,"msg"=>'会员充值收款失败']);
		}else {
			Db::commit();
			return json(['code'=>200,"msg"=>'会员充值收款成功','order_id'=>$paylog['id']]);
		}
	}
	
	/**
	 * 扫一扫收款
	 * */
	public function sys_pay(){
		$pay_type=get_bartype($_POST["mem_card"]);//判断是微信还是支付宝打开
		$order_sn = order_create_no();
		Db::startTrans();
		$res[] = cashier_pay_log($_POST['store_id'],0,$_POST['balance'],8,$order_sn,$pay_type,'扫一扫收款',1,0,$_POST['balance'],$_POST['staff_id']);//订单日志
		$result=bar_pay($_POST["mem_card"],'H480','ea4f13f136c95a617b1acfbda7af6eb1','45a7a757b685f5c890b815839e58ca18',$_POST['balance'],1,$order_sn,'');
		if($result==2 && $res==true){
			Db::commit();
			$order_id = db('paylog')->where('order_sn',$order_sn)->value('id');
			return json(['code'=>200,"msg"=>'收款成功','order_id'=>$order_id]);
		}else{
			Db::rollback();
			return json(["code"=>400,'msg'=>'系统繁忙请稍后再试!']);
		}
	}
	
	/**
	 * 收银员修改操作密码
	 * */
	public function cz_pwd(){
		$where['id'] = $_POST['cz_id'];
		$where['oppass'] = md5_salt($_POST['cz_y_pwd']);
        $member = db('emp')->where($where)->find();
		if(!$member){
			return json(['code'=>400,"msg"=>'原密码不正确']);
		}
		$update['oppass'] =  md5_salt($_POST['cz_up_pwd']);
		$res = db('emp')->where('id',$_POST['cz_id'])->update($update);
		if($res){
			return json(['code'=>200,"msg"=>'修改操作密码成功']);
		}else{
			return json(['code'=>400,"msg"=>'修改操作密码失败']);
		}
	}
	
	/**
	 * 今日收银数据查询
	 * */
	public function get_work(){
		if($_POST){
			$where['add_time']=array('egt',$_POST['log_time']);
			$where['staff_id']=array('eq',$_POST['id']);
			$where['type'] = array('neq',4); 
			$where['is_tk'] = array('eq',0); 
			$field = 'IFNULL(SUM(origin_price-balance),0) as yh_money,IFNULL(SUM(balance),0) as balance';
			$emp = db('paylog')->field($field)->where($where)->find();
			$emp['jz'] = db('paylog')->where($where)->where('type',6)->sum('balance');//记账
			$emp['sm'] = db('paylog')->where($where)->where('type',8)->sum('balance');//桌面收银扫一扫
			$hx_where['time']=array('egt',$_POST['log_time']);
			$hx_where['staff_id']=array('eq',$_POST['id']);
			$hx_where['type'] = array('eq',4); 
			$emp['hx'] =db('consume')->where($hx_where)->sum('num');//核销
			return json(['emp'=>$emp]);
		}
		
	}
}
